import { SocketClient } from "@renderer/plugins/socket";
import voice from "@renderer/assets/voice/notice.mp3";
import request from "@renderer/plugins/axios";
import useNoticeStore from "@renderer/store/modules/notice";
import base from "@renderer/api/base";
import {ref} from "vue"
const baseUrl = base.host
let webSocketClient = ref(null)
const setupNotice = () => {
  //定义websocket连接

  //音频播放
  // 用于获取音频播放授权的函数
  let hasAudioPermission = false;
  function requestAudioPermission() {
    return navigator.mediaDevices
      .getUserMedia({ audio: true })
      .then(() => {
        hasAudioPermission = true;
        console.log("音频播放OK");
      })
      .catch((err) => {
        console.error("获取音频播放授权失败:", err);
      });
  }

  // 初始化函数，检查并获取授权（页面加载时调用）
  async function init() {
    try {
      await requestAudioPermission();
    } catch (err) {
      // 如果授权失败，可以考虑提示用户手动操作或者采取其他备用方案等
      console.log("初始化授权出错，可能无法正常播放音频提醒");
    }
  }
  init();
  const onReceive = (data) => {
    let clientData = JSON.parse(data);
    let clientID = clientData.data.clientId;
    if (clientData.code == 0) {
      //绑定分组
      bindToGroup(clientID);
    }
    if (clientData.code == 5001) {
      const noticeStore = useNoticeStore();
      noticeStore.addNotice(JSON.parse(clientData.data));
      playVoice();
    }
  };
  const playVoice = () => {
    //新订单通知消息
    let audio = new Audio(voice);
    // 加载完成后开始播放
    audio.addEventListener("loadeddata", () => {
      audio.play();
    });
  };
  const bindToGroup = async (clientID) => {
    let site_str = localStorage.getItem("site")
    let siteObj = {}
    let user = JSON.parse(localStorage.getItem("user"))
    if (site_str) {
      siteObj = JSON.parse(site_str)
      await request("api/bind_to_group", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        data: {
          clientId: clientID,
          groupName: `${siteObj.id}`,
          userId: `${user.id}`,
          extend: "",
        },
      });
    }
  };
  const onErrorEvent = (data) => {
    console.log("onErrorEvent", data);
  };

  const onErrorSucceed = (data) => {
    console.log("onErrorSucceed", data);
  };
  let isDev = import.meta.env.MODE == "development"
  const host = baseUrl.replace("http://", "").replace("https://", "")
  let socketUrl = `ws://${host}/ws?systemId=1`; // 替换为实际的WebSocket服务器地址
  if (!isDev) {
    socketUrl = `wss://${host}/ws?systemId=1`; // 替换为实际的WebSocket服务器地址
  }

  if (!webSocketClient.value) {
    webSocketClient.value = new SocketClient(
      socketUrl,
      onReceive,
      onErrorEvent,
      onErrorSucceed,
      "1"
    );
  }

  return {
    webSocketClient
  }
};

export { setupNotice,webSocketClient };
